<template>
  <div style="width: 100%; height: 30px"></div>
  <div class="person">
    <div class="info">
      <div class="avatar"><img :src="userInfo?.headUrl" alt=""></div>
      <div class="info-text">
        <div class="name">
          <span class="text">{{ userInfo?.username }}</span>
          <span class="iconfont icon-bianji" @click="editPerson(userInfo?.id)"></span>
        </div>
        <div class="pwd"><el-button type="primary" plain :icon="Edit"
                                    @click="openEditPwd()">{{ $t('修改密码') }}</el-button></div>
      </div>
    </div>
    <div class="editpwd" @click="addPerson">
      <div class="icon">
        <span class="iconfont icon-quanxianfenpei"></span>
      </div>
      <span class="text">{{ $t('添加管理员') }}</span>
    </div>
  </div>
  <div class="table">
    <el-button type="primary" plain :icon="Delete" style="margin-bottom: 20px" @click="deleteSome">{{ $t('删除') }}</el-button>
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column :label="$t('头像')" width="120">
        <template #default="scope">
          <div class="avatar">
            <img :src="scope.row.headUrl" alt="" />
          </div>
        </template>
      </el-table-column>
      <el-table-column property="username" :label="$t('姓名')" />
      <el-table-column property="mobile" :label="$t('手机号')" />
      <el-table-column property="email" :label="$t('邮箱')" />
<!--      <el-table-column property="password" :label="$t('密码')" />-->
      <el-table-column :label="$t('操作')" width="350">
        <template #default="scope">
          <div class="actions">
            <el-button type="primary" plain :icon="Edit" @click="editPerson(scope.row.id)">{{ $t('修改信息') }}</el-button>
            <el-button type="primary" plain :icon="Refresh" @click="resetPwd(scope.row.id)">{{ $t('重置密码') }}</el-button>
            <el-button type="primary" plain :icon="Delete" @click="deleteItem(scope.row.id)">{{ $t('删除') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" v-if="total > 0">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[100, 200, 300, 400]"
                     :size="size" :disabled="disabled" :background="background" layout="prev, pager, next" :total="total"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      <span class="total">{{ $t('共') }}{{ total }}{{ $t('条') }}</span>
    </div>
    <!-- 管理员录入 -->
    <EditPerson v-if="editPersonDialog" :id="id" @refresh="refresh" @closePersonDialog="closePersonDialog"></EditPerson>
    <!-- 修改密码 -->
    <EditPwd v-if="editpwdDialog" @refresh="refresh" @closeEditPwd="closeEditPwd"></EditPwd>
  </div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, Refresh } from '@element-plus/icons-vue';
import EditPerson from './components/editPerson.vue';
import EditPwd from './components/editPwd.vue';
import { companyUserPage, deleteCompanyUser, resetPwd } from '@/api/index';
export default {
  name: 'Person',
  props: {},
  components: {
    EditPerson,
    EditPwd,
  },
  computed: {
    ...mapGetters({
      fullUserInfo: 'system/userInfo',
    }),
    userInfo() {
      if (this.fullUserInfo) {
        return this.fullUserInfo.userInfo
      } else {
        return {}
      }

    }
  },
  data() {
    return {
      Edit,
      Refresh,
      Delete,
      editPersonDialog: false,
      editpwdDialog: false,
      total: null,
      currentPage: 1,
      pageSize: 20,
      size: 'default',
      disabled: false,
      background: true,
      tableData: [],
      selectedItems: [],
      id: null
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    refresh() {
      this.tableData = [];
      this.currentPage = 1;
      this.fetchData();
    },
    //重置密码
    async resetPwd(id) {
      try {
        const { data } = await resetPwd(id);
        if (data.code == 0) {
          ElMessage({
            type: 'success',
            message: this.$t('该密码重置成功'),
          });
          this.fetchData();
        }
      } catch (error) {
        console.log(error);
      }
    },
    handleSelectionChange(selectedItems) {
      this.selectedItems = selectedItems;
    },
    // 翻页处理
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchData(); // 翻页时重新请求数据
    },
    // 每页显示条数变化处理
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchData(); // 每页条数变化时重新请求数据
    },

    // 获取公司列表数据
    async fetchData() {
      const params = {
        page: this.currentPage,
        count: this.pageSize,
      };
      try {
        const { data } = await companyUserPage({ ...params }); // 使用封装的 API 请求方法
        if (data.code === 0) {
          this.tableData = data.data.records; // 更新表格数据
          this.total = +data.data.total; // 更新总数据条数
          this.pageSize = +data.data.size; // 设置每页条数
        }
      } catch (error) {
        console.log(error);
      }
    },
    deleteItem(id) {
      ElMessageBox.confirm(
          this.$t('删除该企业管理员后不能恢复，确定要删除吗？'),
          this.$t('删除确认'),
          {
            confirmButtonText: this.$t('删除'),
            cancelButtonText: this.$t('取消'),
            type: 'warning',
          },
      )
          .then(async () => {
            try {
              const { data } = await deleteCompanyUser([id]); // 使用数组传递单个 ID
              if (data.code === 0) {
                ElMessage({
                  type: 'success',
                  message: this.$t('删除成功'),
                });
                this.fetchData(); // 删除后刷新数据
              } else {
                ElMessage({
                  type: 'error',
                  message: data.message || this.$t('删除失败，请重新操作'),
                });
              }
            } catch (error) {
              console.log(error);
              ElMessage({
                type: 'error',
                message: this.$t('删除请求失败，请稍后再试'),
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: this.$t('取消删除'),
            });
          });
    },
    deleteSome() {
      const selectedIds = this.selectedItems.map(
          (item) => item.id,
      );

      if (selectedIds.length === 0) {
        ElMessage({
          type: 'warning',
          message: this.$t('请选择要删除的企业管理员！'),
        });
        return;
      }

      ElMessageBox.confirm(
          this.$t(`已选择`) + ' ' + selectedIds.length + ' ' + this.$t('条企业管理员数据，删除该企业管理员后不能恢复，确定要删除吗？'),
          this.$t('删除确认'),
          {
            confirmButtonText: this.$t('删除'),
            cancelButtonText: this.$t('取消'),
            type: 'warning',
          },
      )
          .then(async () => {
            try {
              const { data } = await deleteCompanyUser(selectedIds);
              if (data.code === 0) {
                ElMessage({
                  type: 'success',
                  message: this.$t('删除成功'),
                });
                this.fetchData();
              } else {
                ElMessage({
                  type: 'error',
                  message: data.message || this.$t('删除失败，请重新操作'),
                });
              }
            } catch (error) {
              console.log(error);
              ElMessage({
                type: 'error',
                message: this.$t('删除请求失败，请稍后再试'),
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: this.$t('取消删除'),
            });
          });
    },
    // 修改个人信息
    editPerson(id) {
      this.id = id;
      this.editPersonDialog = true;
    },
    // 添加管理员
    addPerson() {
      this.id = null;
      this.editPersonDialog = true;
    },
    // 修改密码
    openEditPwd() {
      this.editpwdDialog = true;
    },
    closePersonDialog() {
      this.editPersonDialog = false;
    },
    closeEditPwd() {
      this.editpwdDialog = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-button {
  transition: 0.3s ease;
  background: #303f2e;
  border-color: $color;

  &:hover {
    background-color: $color;
    border-color: $color;
  }
}

.person {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;

  .info {
    display: flex;

    .avatar {
      width: 90px;
      height: 90px;
      background: #404040;
      border-radius: 50%;
      margin-right: 30px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .info-text {
      .iconfont {
        color: #ffffff;
        font-size: 20px;
        cursor: pointer;
        transition: 0.3s ease;
        margin-left: 23px;

        &:hover {
          color: $color;
        }
      }

      .name {
        margin-bottom: 12px;
        margin-top: 15px;

        .text {
          font-size: 24px;
          color: #ffffff;
          font-weight: 500;
        }
      }

      .pwd {
        font-size: 18px;
        color: #ffffff;
        font-weight: 400;
      }
    }
  }

  .editpwd {
    width: 176px;
    height: 50px;
    background: #303f2e;
    border-radius: 30px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: 0.3s ease;

    .icon {
      width: 32px;
      height: 32px;
      background: $color;
      color: #fff;
      text-align: center;
      line-height: 32px;
      border-radius: 50%;
      margin-right: 10px;
    }

    .text {
      font-weight: 400;
      font-size: 16px;
      color: #ffffff;
      transition: 0.3s ease;
    }

    &:hover {
      background: #fff;

      .text {
        color: $color;
      }
    }
  }
}

.table {
  .avatar {
    width: 50px;
    height: 50px;
    background: #d9d9d9;
    border-radius: 50%;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .actions {
    .iconfont {
      font-size: 20px;
      transition: 0.3s ease;
      margin-right: 26px;
      cursor: pointer;

      &:hover {
        color: $color;
      }
    }
  }
}
</style>
